package com.aida.evil.eda.Login;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.aida.evil.aida.R;
import com.aida.evil.eda.Data.NetworkData;
import com.aida.evil.eda.Data.UserData;
import com.aida.evil.eda.Intent.IntentData;
import com.aida.evil.eda.MyView.ListViewForScrollView;
import com.aida.evil.eda.SQL.UserData.User_Sql;
import com.aida.evil.eda.SQL.UserData.User_data;
import com.aida.evil.eda.Toast.CustomSuperActivityToast;
import com.aida.evil.eda.Volley.VolleyHandler;
import com.aida.evil.eda.Volley.VolleyHttpRequest;
import com.aida.evil.eda.Window.CustomDialog;
import com.dd.CircularProgressButton;
import com.github.johnpersano.supertoasts.SuperActivityToast;
import com.github.johnpersano.supertoasts.SuperToast;
import com.github.johnpersano.supertoasts.util.OnClickWrapper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.picasso.Picasso;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/****************************************************
 * Login
 * 作者：白雨濃  evil
 * 时间：16-2-9 21:47
 * 邮箱：evilbai@foxmail.com
 * 页面用途：登陆界面
 ****************************************************/

public class Login extends AppCompatActivity
{
    private static final String BREAKSTRING = ">-<";
    private final static String URL = "http://" + NetworkData.ServiceIP + "/Login";//传递用户IMEI的url


    private EditText userPhoneNum_EditText, password_EditText;/*手机号和密码输入框*/
    private CircularProgressButton submit_button;/*登陆按钮*/
    private TextView register_button;/*注册按钮*/
    private CheckBox remember_CheckBox;/*记住密码*/
    private boolean remember_bool = false;/*是否在数据库中读取的密码*/

    private String userPhoneNum, password;/*手机号,密码*/

    /**
     * 主要作用是在注册界面finish();掉之后，登陆界面能获取到注册界面的手机号直接填写
     */
    @Override
    protected void onResume()
    {
        super.onResume();
        if (!UserData.DATA_PHONENUM.isEmpty())
        {
            userPhoneNum_EditText.setText(UserData.DATA_PHONENUM);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        /*动态加载背景图片，以免耗用ui线程时间*/
        Picasso.with(this).load(R.mipmap.login_background)
                .into((ImageView) findViewById(R.id.login_background));

        findviewById();

        setEditTextString();/*在数据库中读取账号密码*/
        submit_button.setIndeterminateProgressMode(true);
        remember_CheckBox.setChecked(true);
        onClick();
    }


    /**
     * 查找控件
     */
    private void findviewById()
    {
        userPhoneNum_EditText = (EditText) findViewById(R.id.login_userPhoneNum);
        password_EditText = (EditText) findViewById(R.id.login_password);
        submit_button = (CircularProgressButton) findViewById(R.id.login_submit);
        register_button = (TextView) findViewById(R.id.login_register);
        remember_CheckBox = (CheckBox) findViewById(R.id.login_checkBox);
    }

    /**
     * 设置输入框内容
     */
    private void setEditTextString()
    {
        User_Sql user_sql = new User_Sql(Login.this);
        List<User_data> user_datas = user_sql.queryAll();
        if (user_datas.size() > 0)
        {
            User_data user_data = user_datas.get(0);
            //if(user_data.getUserPhoneNum().equals(UserData.DATA_PHONENUM))
            userPhoneNum_EditText.setText(user_data.getUserPhoneNum());
            password_EditText.setText(user_data.getPassword());
            remember_bool = true;

            //login();
        }
    }

    /**
     * 得到输入框的内容
     */
    private void getEditTextString()
    {
        userPhoneNum = userPhoneNum_EditText.getText().toString();
        UserData.DATA_PHONENUM = userPhoneNum;
        if (remember_bool)
        {
            password = password_EditText.getText().toString();
        }
        else
        {
            password = Encrypt_MD5.GetMD5Code(password_EditText.getText().toString());/*直接进行MD5加密*/
        }
    }

    /**
     * 点击事件
     */
    private void onClick()
    {
        /*注册界面跳转*/
        register_button.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                startActivity(new Intent(Login.this, Register.class));
            }
        });

        /*点击密码框消除密码*/
        password_EditText.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                password_EditText.setText("");
            }
        });

        /*密码框改变监听，如果改变，则获取密码时候需要加密*/
        password_EditText.addTextChangedListener(new ListViewForScrollView(this)
        {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count)
            {
                super.onTextChanged(s, start, before, count);
                remember_bool = false;
            }
        });


        /*登陆按钮*/
        submit_button.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                login();
            }
        });

    }

    /*登陆事件*/
    private void login()
    {
        /*登陆*/
        if (submit_button.getProgress() == -1 || submit_button.getProgress() == 100)
        {
            submit_button.setProgress(0);
        }
        else
        {
            submit_button.setProgress(50);
            getEditTextString();
            if (!userPhoneNum.isEmpty() && !password_EditText.getText().toString().isEmpty())
            {
                toNetWork();
            }
            else
            {
                CustomSuperActivityToast.makeText(Login.this, "输入为空", "确定").show();
                submit_button.setProgress(0);
            }
        }
        User_Sql user_sql = new User_Sql(Login.this);

                /*记住密码*/
        if (remember_CheckBox.isChecked())
        {
            user_sql.update(userPhoneNum, password);
        }
        else
        {
            user_sql.deleteAll();
        }
    }

    /**
     * 登陆操作
     */
    private void toNetWork()
    {
        VolleyHandler<String> stringVolleyHandler = new VolleyHandler<String>()
        {
            @Override
            public void reqSuccess(String response)
            {
                Analyse(response);
            }

            @Override
            public void reqError(String error)
            {
                submit_button.setProgress(-1);
                CustomSuperActivityToast.makeText(Login.this, "网络错误", "确认").show();
            }

            /**
             * 解析返回值
             */
            private void Analyse(String response)
            {
                /*返回值为No,则为未注册*/
                if (response.equals("No"))
                {
                    submit_button.setProgress(-1);
                    CustomSuperActivityToast.makeText(Login.this, "该手机号未注册,请前往注册!", "注册", new SuperToast.OnClickListener()
                    {
                        @Override
                        public void onClick(View view, Parcelable token)
                        {
                            startActivity(new Intent(Login.this, Register.class));
                        }
                    }).setBackground(SuperToast.Background.RED).show();
                }
                /*返回值为No,则为密码错误*/
                else
                {
                    if (response.equals("Error"))
                    {
                        submit_button.setProgress(-1);

                        CustomSuperActivityToast.makeText(Login.this, "密码错误,请重新输入", "确认", new SuperToast.OnClickListener()
                        {
                            @Override
                            public void onClick(View view, Parcelable token)
                            {
                                startActivity(new Intent(Login.this, Register.class));
                            }
                        }).setBackground(SuperToast.Background.RED).show();
                    }
                /*输入正确,进行解析*/
                    else
                    {
                        LoginBean loginBean;
                        {
                            Type type = new TypeToken<LoginBean>()
                            {
                            }.getType();
                            loginBean = new Gson().fromJson(response, type);
                        }
                        {
                            if (loginBean.UserPhoneNum.equals(UserData.DATA_PHONENUM))
                            {
                                UserData.DATA_USERNAME = loginBean.UserName;
                                UserData.DATA_PASSWORD = password;
                                UserData.DATA_INTEGRAL = loginBean.UserIntegral;
                                UserData.DATA_LASTITEMID = loginBean.LastItemID;
                            /*为0时为白名单,为1时为黑名单*/
                                if (loginBean.BlackList == 0)
                                {
                                    UserData.DATA_BLACKLIST = true;
                                    Intent intent = new Intent();
                                    intent.setAction(new IntentData().getWelcome_to_mainactivity());
                                    intent.addCategory(new IntentData().getCategory_DEFAULT());
                                    startActivity(intent);
                                    finish();
                                }
                                else
                                {
                                    UserData.DATA_BLACKLIST = false;
                                    CustomDialog.Builder builder = new CustomDialog.Builder(Login.this);
                                    builder.setTitle("提示");
                                    builder.setMessage("由于您的违法操作,您已经被拉入黑名单\n请退出软件,谢谢!");
                                    builder.setCanceledOnTouchOutside(false);
                                    builder.setBackPressed(false);
                                    builder.setPositiveButton("退出", new DialogInterface.OnClickListener()
                                            {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which)
                                                {
                                                    finish();
                                                }
                                            }
                                    );
                                    builder.show();
                                }
                            }
                        }
                    }
                }
            }

        };
        Map<String, String> map = new HashMap<>();
        map.put("userPhoneNum", userPhoneNum);
        map.put("password", password);
        map.put("userIMEI", UserData.DATA_IMEI);
        VolleyHttpRequest.String_request(URL, map, stringVolleyHandler);
    }

    private class LoginBean
    {
        protected String UserPhoneNum;
        protected String UserIMEI;
        protected String UserImg;
        protected String UserName;
        protected int UserIntegral;
        protected String LastItemID;
        protected int BlackList;
    }

}